const path = require("path");
const { defineConfig, build } = require("vite");
const vue = require("@vitejs/plugin-vue");
const vueJsx = require("@vitejs/plugin-vue-jsx");
const fsExtra = require("fs-extra");
const fs = require("fs");
// 打包入口文件夹
const entryDir = path.resolve(__dirname, "../packages");
// 出口文件夹
const outDir = path.resolve(__dirname, "../lib");

// vite基础配置
const baseConfig = defineConfig({
  configFile: false,
  publicDir: false,
  plugins: [vue(), vueJsx()],
});

// rollup配置
const rollupOptions = {
  external: ["vue", "vue-router"], //不会安装
  output: {
    globals: {
      vue: "Vue",
    },
  },
};

// 全量打包构建
const buildAll = async () => {
  await build({
    ...baseConfig,
    build: {
      rollupOptions,
      lib: {
        entry: path.resolve(entryDir, "index.ts"),
        name: "index",
        fileName: "index",
        formats: ["es", "umd"],
      },
      outDir,
    },
  });
};

/**
 * 单组件打包构建
 * @param {*} name  组件名称
 */
const buildSingle = async (name) => {
  await build({
    ...baseConfig,
    build: {
      rollupOptions,
      lib: {
        entry: path.resolve(entryDir, name),
        name: "index",
        fileName: "index",
        formats: ["es", "umd"],
      },
      outDir: path.resolve(outDir, name),
    },
  });
};

/**
 * 每个组件生成package.json
 * @param {*} name 组件名称
 * npm i -D fs-extra
 */
const createPackageJson = (name) => {
  const fileStr = `
  {
    "name":"${name}",
    "main":"index.umd.js",
    "module":"index.es.js",
    "style":"styles.css"
  }
  `;
  // 输出
  fsExtra.outputFile(
    path.resolve(outDir, `${name}/package.json`),
    fileStr,
    "utf-8"
  );
  //  赋值public/index.d.ts 到每个组件下
  fs.readFile(
    path.resolve(__dirname, "../public/index.d.ts"),
    "utf8",
    (err, data) => {
      if (err) return console.error(err);
      fsExtra.outputFile(
        path.resolve(outDir, `${name}/index.d.ts`),
        data,
        "utf-8"
      );
    }
  );
};

// 打包成库
const buildLib = async () => {
  await buildAll();
  // 获取组件名称组成的数组
  const components = fs.readdirSync(entryDir).filter((name) => {
    const componentDir = path.resolve(entryDir, name);

    // 判断是不是目录
    const isDir = fs.lstatSync(componentDir).isDirectory();
    return isDir && fs.readdirSync(componentDir).includes("index.ts"); //是目录并且有index.ts文件
  });

  // 循环构建
  for (const name of components) {
    if (name == "utils") return;
    await buildSingle(name);
    await copyFile();
    createPackageJson(name);
  }
};
const copyFile = async () => {
  try {
    //  赋值public/index.d.ts 到lib
    let data2 = fs.readFileSync(
      path.resolve(__dirname, "../public/index.d.ts"),
      "utf-8"
    );
    fsExtra.outputFile(path.resolve(outDir, "index.d.ts"), data2, "utf-8");
  } catch (err) {
    // 出错了
  }
};

buildLib();
